<template>
  <div class="container">
    <Header :showRefresh="false" @refresh="() => {}">
      <template #leftTitle>
        <router-link to="/event/list">事件列表</router-link>
        <el-icon class="v-align-top"> <arrow-right-bold /> </el-icon>
      </template>
    </Header>

    <section class="page-main edit-box">
      <el-form
        label-position="right"
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
      >
        <li>
          <el-form-item label="事件名称" prop="evtName">
            <el-input v-model="ruleForm.evtName" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="所属应用" prop="appId">
            <el-select
              style="width: 100%"
              v-model="ruleForm.appId"
              placeholder="请选择"
              filterable
              remote
              :remote-method="appRemote"
              @change="appRemote('')"
            >
              <el-option
                :label="item.appName + '-' + item.orgName"
                :value="item.id"
                v-for="(item, index) in appList"
                :key="index"
              >
              </el-option>
              <el-pagination
                small
                background
                @current-change="getAppList"
                :page-size="10"
                layout="prev, pager, next"
                :total="appListTotal"
              >
              </el-pagination>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="消费者总数限制" prop="subscriberCnt">
            <el-input v-model="ruleForm.subscriberCnt" type="Number" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="主题" prop="topicName">
            <el-input v-model="ruleForm.topicName" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="频率" prop="rate">
            <el-input v-model="ruleForm.rate" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="失败保留天数" prop="failValidDays">
            <!-- <el-input v-model="ruleForm.failValidDays" /> -->
            <el-select
              v-model="ruleForm.failValidDays"
              placeholder="请选择"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="(item, index) in saveDayList"
                :key="index"
                :label="item + '天'"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="服务标签">
            <el-select v-model="ruleForm.tags" placeholder="请选择" multiple style="width: 100%">
              <el-option
                :label="item.label"
                :value="item.id"
                v-for="(item, index) in tagsList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="是否上传IRS" prop="irsAppId">
            <el-radio-group v-model="ruleForm.uploadIrs">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </li>
        <!-- 0223022新增 -->
        <li>
          <el-form-item label="共享类型" prop="shareType">
            <el-select v-model="ruleForm.shareType" placeholder="请选择" style="width: 100%">
              <el-option
                :label="item"
                :value="index"
                v-for="(item, index) in shareList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="领域分类" prop="domainType">
            <el-select v-model="ruleForm.domainType" placeholder="请选择" style="width: 100%">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item, index) in domainList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="敏感等级" prop="sensitiveLevel">
            <el-select v-model="ruleForm.sensitiveLevel" placeholder="请选择" style="width: 100%">
              <el-option
                :label="item"
                :value="index"
                v-for="(item, index) in sensitiveList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>

        <li class="affiliation-app">
          <el-form-item label="运维人员" class="from" prop="createdUserCode">
            <el-input v-model="ruleForm.createdUserName" disabled />
            <el-input
              v-model="ruleForm.createdUserCode"
              disabled
              v-show="false"
            />
            <el-button type="primary" class="new-btn" @click="selectZzdUser"
              >选择</el-button
            >
          </el-form-item>
        </li>

        <li>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="ruleForm.memo" />
          </el-form-item>
        </li>
        <li>
          <el-form-item label="服务转事件" prop="memo">
            <el-switch
              v-model="ruleForm.svcToEvt"
              active-text="是"
              inactive-text="否"
            ></el-switch>
          </el-form-item>
        </li>
        <el-divider></el-divider>
        <div v-if="ruleForm.svcToEvt">
          <li>
            <el-form-item label="选择服务" prop="memo">
              <el-select
                v-model="ruleForm.svcId"
                placeholder="请选择"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(item, index) in serviceList"
                  :key="index"
                  :label="item.svcName"
                  :value="item.svcId"
                />
              </el-select>
            </el-form-item>
          </li>
          <li>
            <el-form-item label="定时" prop="memo">
              <el-input v-model="ruleForm.cron" disabled class="append-button">
                <template #append>
                  <el-button type="primary" @click="showDialog"
                    >生成 cron</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
          </li>
        </div>
        <h4 class="divider">参数校验</h4>
        <PamarsCheck v-model="ruleForm.resEvtInParamsList"></PamarsCheck>
        <footer class="drawer-footer">
          <el-button type="primary" @click="eventSubmit" :loading="loading">
            确 定
          </el-button>
          <el-button @click="beforeClose">取 消</el-button>
        </footer>
      </el-form>
    </section>
    <el-dialog title="生成 cron" v-model="showCron">
      <vcrontab
        @hide="showCron = false"
        @fill="crontabFill"
        :expression="expression"
      ></vcrontab>
    </el-dialog>
    <!-- 新增/编辑应用 -->
    <EditDrawer v-model="showEdit" :item="currentItem" @update-list="refresh" />
    <SelectUser
      @query-change="queryChange"
      v-model="showZzdSelcet"
    ></SelectUser>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ArrowRightBold } from "@element-plus/icons-vue";
import { computed, ref, onMounted, toRefs, reactive, watch } from "vue";
import { updateEvent, createEvent, getEventDetail } from "@/api/event.js";
import Header from "@/components/Header.vue";
import vcrontab from "@/components/VcronTab/Crontab.vue";
import useEditDrawer from "@/hooks/useEditDrawer";
import { useListManage } from "@/hooks";
import { getServieList ,getTagsPageList} from "@/api/service.js";
import { getAppPageList, getAppDetail } from "@/api/application";
import { isChartacter, isPositiveInteger, createArray } from "@/utils/index.js";
import { useRoute, useRouter } from "vue-router";
import PamarsCheck from "./components/PamarsCheck.vue";
import EditDrawer from "@/views/application/components/EditDrawer.vue";
import { deepClone } from "../../../utils";
import SelectUser from "@/views/system/user/select-user.vue";
const route = useRoute();
const router = useRouter();
const props = defineProps();
const emit = defineEmits();
const id = route.query.id;
const editType = id ? "update" : "create";
const DEFAULT_FORM = {
  evtName: "",
  appId: "",
  subscriberCnt: "",
  svcToEvt: false,
  rate: 1,
  resEvtInParamsList: [
    {
      id: 1000,
      paramName: "",
      paramNameCn: "",
      required: 0,
      type: "",
      children: [],
    },
  ],
};

// 自定义提交
const eventSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    let { paramName, paramNameCn } = ruleForm.value.resEvtInParamsList[0];
    let ruleFormObj = deepClone(ruleForm.value);

    if (!(paramName && paramNameCn)) {
      ruleFormObj.resEvtInParamsList = [];
    }
    console.log(valid);
    if (valid) {
      let typeBloon = editType === "update";
      let tipStr = typeBloon ? "编辑成功" : "新增成功";
      let axiosFn = typeBloon ? updateEvent : createEvent;
      const res = await axiosFn(ruleFormObj);
      if (res.status === 200 || res.status === 201) {
        ElMessage.success(tipStr);
        router.push({ name: "EventList" });
      }
      loading.value = false;
    } else {
      console.log("error submit!!");
      loading.value = false;
      return false;
    }
  });
};

const state = reactive({
  appList: [],
  appListTotal: 0,
  serviceList: [],
  serviceSwitch: false,
  expression: "",
  showCron: false,
  requestData: [{ defaultValue: "" }],
  appSearchKey: "",
});
const {
  appList,
  appListTotal,
  serviceList,
  serviceSwitch,
  expression,
  showCron,
  requestData,
  appSearchKey,
} = toRefs(state);

const { handleCreate, showEdit, currentItem, refresh, list } = useListManage(
  props,
  emit,
  {
    getItems: function () {},
    query: null,
    getDetail: function () {},
    deleteItem: function () {},
  }
);
console.log("state.appListInfo.list", state.appListInfo);

// 应用列表
const getAppList = async (current = 1) => {
  let params = {
    search: state.appSearchKey,
    current,
    size: 10,
  };
  console.log(params);
  let { data } = await getAppPageList(params);
  console.log("applist", data);
  state.appList = data.list;
  console.log(state.appList);
  state.appListTotal = data.total;
  console.log(data);
};
const appRemote = (value) => {
  state.appSearchKey = value;
  getAppList();
};
// 应用详情
const getAppDetailInfo = async (id) => {
  var newArr = state.appList.find(function (item) {
    return item.id === id;
  });
  if (!newArr) {
    let { data } = id ? await getAppDetail(id) : {};
    console.log(data);
    state.appList.push(data);
  }
  // console.log(data);
};

const {
  visible,
  direction,
  loading,
  close,
  submit,
  ruleFormRef,
  ruleForm,
  title,
} = useEditDrawer({
  createApi: createEvent,
  editApi: updateEvent,
  defaultForm: DEFAULT_FORM,
  emit,
  type: editType,
  props: { type: editType },
});

const saveDayList = createArray(11);

const beforeClose = () => {
  router.push({ name: "EventList" });
};

// 已上线服务类别
const getServieApiList = async () => {
  let { data } = await getServieList({ current: 1, size: 999, onlineSts: "A" });
  state.serviceList = data.list;
};

const getDetail = async () => {
  if (id) {
    let { data } = await getEventDetail(id);
    ruleForm.value = {
      ...DEFAULT_FORM,
      ...data,
    };
  }
};

watch(loading, (val) => {
  // 加载完成路由到列表页
  if (!val) {
    router.push({ name: "EventList" });
  }
});
// 应用列表加载完成后回调应用名称
watch(
  () => state.appList,
  (val, old) => {
    if (id) {
      getAppDetailInfo(ruleForm.value.appId);
    }
  }
);

// 服务标签列表
const tagsList = ref([]);
const getTagsList = () => {
  let res = getTagsPageList();
  tagsList.value = res;
};


onMounted(async () => {
  getServieApiList();
  getDetail();
  getAppList();
  getTagsList()
});

// 验证
const rules = computed(() => {
  const baseRules = {
    evtName: [{ required: true, message: "请输入事件名称", trigger: "blur" }],
    appId: [{ required: true, message: "请选择所属应用", trigger: "change" }],
    topicName: [{ required: true, validator: isChartacter, trigger: "blur" }],
    subscriberCnt: [
      { required: true, message: "请输入消费者总数限制", trigger: "blur" },
    ],
    rate: [{ required: true, validator: isPositiveInteger, trigger: "blur" }],
  };
  if (props.type === "update") {
    // 如果是编辑
  }
  return baseRules;
});
// 生成cron
const crontabFill = (value) => {
  ruleForm.value.cron = value;
};
const showDialog = () => {
  state.expression = ruleForm.value.cron;
  state.showCron = true;
};

const shareList = ["受限共享", "无条件共享", "非共享"];

const domainList = [
  { id: 1, name: "党政机关整体智治" },
  { id: 2, name: "数字政府" },
  { id: 3, name: "数字经济" },
  { id: 4, name: "数字社会" },
  { id: 5, name: "数字法治" },
  { id: 10, name: "其他" },
];

const sensitiveList = [
  "1级(不敏感) ",
  "2级(低敏感) ",
  "3级(较敏感) ",
  "4级(敏感) ",
  "5级(极敏感) ",
];
// 浙政钉用户选择
const selectZzdUser = () => {
  showZzdSelcet.value = true;
};
const showZzdSelcet = ref(false);
const queryChange = (val) => {
  ruleForm.value.createdUserCode = val.id;
  ruleForm.value.createdUserName = val.userName;
  showZzdSelcet.value = false;
  console.log(showZzdSelcet.value);
};
</script>

<style lang="scss" scoped>
$height: 50px;

.drawer-main {
  height: calc(100% - 50px);
}

.drawer-footer {
  text-align: right;
  height: $height;
  line-height: $height;
}

.tip-text {
  text-align: right;
  color: #ca2e2e;
  margin-top: -10px;
}

.edit-box {
  li {
    width: 50%;
    display: inline-block;
    padding-right: 40px;
  }
}
</style>
